<template>
  <div class="key-value-list">
    <div class="list-header">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>添加配置
      </el-button>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索Key或描述"
          clearable
          class="search-input"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="filterType"
          placeholder="筛选类型"
          clearable
          class="type-filter"
          @change="handleFilter"
        >
          <el-option
            v-for="type in typeOptions"
            :key="type"
            :label="type"
            :value="type"
          />
        </el-select>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      stripe
      style="width: 100%"
      :empty-text="loading ? '加载中...' : '暂无配置数据'"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="id" label="ID" width="80" sortable="custom" />
      
      <el-table-column prop="key" label="Key" min-width="200" sortable="custom">
        <template #default="{ row }">
          <el-tooltip v-if="row.key && row.key.length > 30" :content="row.key" placement="top">
            <span>{{ row.key.substring(0, 30) }}...</span>
          </el-tooltip>
          <span v-else>{{ row.key || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="type" label="类型" width="150" sortable="custom">
        <template #default="{ row }">
          <el-tag v-if="row.type" type="info">{{ row.type }}</el-tag>
          <span v-else class="text-placeholder">-</span>
        </template>
      </el-table-column>

      <el-table-column prop="value" label="值" min-width="250">
        <template #default="{ row }">
          <div class="value-cell">
            <el-tooltip
              placement="top"
              effect="dark"
              :disabled="!getValuePreview(row.value)"
            >
              <template #content>
                <div class="value-tooltip-content">{{ getValueDisplay(row.value) }}</div>
              </template>
              <span class="value-preview">{{ getValuePreview(row.value) || '-' }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="desc" label="描述" min-width="200">
        <template #default="{ row }">
          <el-tooltip
            v-if="row.desc && row.desc.length > 50"
            :content="row.desc"
            placement="top"
            effect="light"
          >
            <span>{{ row.desc.substring(0, 50) }}...</span>
          </el-tooltip>
          <span v-else>{{ row.desc || '无描述' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="updatedAt" label="更新时间" width="180" sortable="custom">
        <template #default="{ row }">
          {{ formatDate(row.updatedAt) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 编辑/创建对话框 -->
    <KeyValueDialog
      v-model="dialogVisible"
      :data="currentItem"
      :mode="dialogMode"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search, Refresh } from '@element-plus/icons-vue';
import { keyValueApi, type KeyValue, type KeyValueQueryParams } from '../../api/keyValue';
import KeyValueDialog from './KeyValueDialog.vue';
import { debounce } from '../../utils/common';

// Props
interface Props {
  // 是否自动加载数据（按需加载）
  autoLoad?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  autoLoad: false,
});

// Emits
const emit = defineEmits<{
  (e: 'refresh'): void;
}>();

// 状态
const loading = ref(false);
const tableData = ref<KeyValue[]>([]);
const searchQuery = ref('');
const filterType = ref('');
const typeOptions = ref<string[]>([]);

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 20,
  total: 0,
});

// 排序
const sortParams = reactive<{
  prop?: string;
  order?: 'ascending' | 'descending';
}>({});

// 对话框
const dialogVisible = ref(false);
const dialogMode = ref<'create' | 'edit'>('create');
const currentItem = ref<KeyValue | null>(null);

// 计算属性：获取类型选项（从现有数据中提取）
const updateTypeOptions = () => {
  const types = new Set<string>();
  tableData.value.forEach(item => {
    if (item.type) {
      types.add(item.type);
    }
  });
  typeOptions.value = Array.from(types).sort();
};

// 格式化日期
const formatDate = (date?: Date | string) => {
  if (!date) return '-';
  const d = typeof date === 'string' ? new Date(date) : date;
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

// 获取值的预览（用于表格显示 - 单行省略）
const getValuePreview = (value: any): string => {
  if (value === null || value === undefined) return '';
  if (typeof value === 'string') return value;
  if (typeof value === 'number' || typeof value === 'boolean') return String(value);
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
};

// 获取值的完整显示（用于tooltip - 格式化JSON，显示3行）
const getValueDisplay = (value: any): string => {
  if (value === null || value === undefined) return '-';
  if (typeof value === 'string') {
    // 如果是字符串，尝试解析为JSON
    try {
      const parsed = JSON.parse(value);
      return JSON.stringify(parsed, null, 2);
    } catch {
      // 如果不是JSON，直接返回字符串
      return value;
    }
  }
  if (typeof value === 'number' || typeof value === 'boolean') {
    return String(value);
  }
  try {
    // 格式化JSON，限制为3行
    const formatted = JSON.stringify(value, null, 2);
    const lines = formatted.split('\n');
    if (lines.length > 3) {
      return lines.slice(0, 3).join('\n') + '\n...';
    }
    return formatted;
  } catch {
    return String(value);
  }
};

// 加载数据
const loadData = async () => {
  if (loading.value) return;
  
  loading.value = true;
  try {
    // 如果有搜索条件，使用 query 接口；否则使用 getList 接口
    const hasSearch = searchQuery.value || filterType.value;
    
    if (hasSearch) {
      // 使用搜索接口
      const conditions: Record<string, any> = {
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
      };

      // 搜索条件
      if (searchQuery.value) {
        // 搜索 key 或 desc
        conditions.key = searchQuery.value;
        conditions.desc = searchQuery.value;
      }

      // 类型筛选
      if (filterType.value) {
        conditions.type = filterType.value;
      }

      const response = await keyValueApi.query(conditions);
      
      if (response && response.data) {
        const data = response.data;
        tableData.value = data.pageData || data.list || [];
        pagination.total = data.total || 0;
        pagination.pageNo = data.pageNo || pagination.pageNo;
        pagination.pageSize = data.pageSize || pagination.pageSize;
        
        // 更新类型选项
        updateTypeOptions();
      } else {
        tableData.value = [];
        pagination.total = 0;
      }
    } else {
      // 使用普通列表接口
      const params: KeyValueQueryParams = {
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
      };

      // 排序
      if (sortParams.prop && sortParams.order) {
        // 后端可能需要特定的排序参数，这里先不处理，由后端决定
      }

      const response = await keyValueApi.getList(params);
      
      if (response && response.data) {
        const data = response.data;
        tableData.value = data.pageData || data.list || [];
        pagination.total = data.total || 0;
        pagination.pageNo = data.pageNo || pagination.pageNo;
        pagination.pageSize = data.pageSize || pagination.pageSize;
        
        // 更新类型选项
        updateTypeOptions();
      } else {
        tableData.value = [];
        pagination.total = 0;
      }
    }
  } catch (error: any) {
    console.error('加载数据失败:', error);
    ElMessage.error(error.message || '加载数据失败');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索（带防抖）
const handleSearch = debounce(() => {
  pagination.pageNo = 1;
  loadData();
}, 500);

// 筛选
const handleFilter = () => {
  pagination.pageNo = 1;
  loadData();
};

// 刷新
const handleRefresh = () => {
  loadData();
};

// 分页变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNo = 1;
  loadData();
};

const handlePageChange = (page: number) => {
  pagination.pageNo = page;
  loadData();
};

// 排序变化
const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  sortParams.prop = prop;
  sortParams.order = order as 'ascending' | 'descending';
  loadData();
};

// 创建
const handleCreate = () => {
  currentItem.value = null;
  dialogMode.value = 'create';
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: KeyValue) => {
  currentItem.value = { ...row };
  dialogMode.value = 'edit';
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (row: KeyValue) => {
  if (!row.id) {
    ElMessage.error('无效的配置项');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除配置项 "${row.key}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await keyValueApi.delete(row.id);
    ElMessage.success('删除成功');
    loadData();
    emit('refresh');
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error(error.message || '删除失败');
    }
  }
};

// 对话框成功回调
const handleDialogSuccess = () => {
  loadData();
  emit('refresh');
};

// 暴露方法供父组件调用
defineExpose({
  loadData,
  refresh: loadData,
});

// 监听autoLoad，如果为true则自动加载
watch(() => props.autoLoad, (newVal) => {
  if (newVal) {
    loadData();
  }
}, { immediate: true });

// 如果autoLoad为true，组件挂载时加载数据
onMounted(() => {
  if (props.autoLoad) {
    loadData();
  }
});
</script>

<style scoped>
.key-value-list {
  width: 100%;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
  flex-wrap: wrap;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 200px;
}

.type-filter {
  width: 150px;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.value-cell {
  max-width: 100%;
  overflow: hidden;
  position: relative;
}

.value-preview {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: break-all;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  cursor: default;
}

.value-tooltip-content {
  max-width: 500px;
  max-height: 80px;
  overflow: hidden;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
}

.text-placeholder {
  color: var(--el-text-color-placeholder);
}

@media (max-width: 768px) {
  .list-header {
    flex-direction: column;
    align-items: stretch;
  }

  .header-actions {
    width: 100%;
    flex-direction: column;
  }

  .search-input,
  .type-filter {
    width: 100%;
  }
}
</style>

